<template>
  <div class="content">
    <div>
      <van-sticky>
        <div class="searchBar emphasize-inset">
          <van-search
              id="search"
              v-model="search_value"
              show-action
              background="#f2f3f5"
              left-icon="search"
              placeholder="请输入搜索关键词"
              @search="onSearch"
          >
            <template #action>
              <van-button
                  plain
                  hairline
                  size="small"
                  color="#44cef6"
                  type="default"
                  @click="onSearch"
              >搜索
              </van-button>
            </template>
          </van-search>
        </div>
      </van-sticky>
    </div>
    <div class="tips">
      <van-notice-bar
          left-icon="info-o"
          color="#1989fa"
          background="#70f3ff"
          text="当前歌曲列表"
      />
    </div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div style="min-height: 100vh;" v-show="isInit">

        <div class="songs" v-show="raw_list.length>0">
          <div v-for="(item) in raw_list" :key="item.music_id">
            <div class="list-item emphasize-dark" @click="toSongInfo(item)">
              <div class="list-header">
                <div class="song-info">
                  <h3 class="list-title">{{ item.music_name }}</h3>
                </div>
                <div class="icon_group">
                  <van-icon :name="is_play===item.music_id?'pause-circle':'play-circle'" size="30px" color="white"
                            @click.stop="playMusic(is_play===item.music_id,item.music_id,item.music_name)"/>
                  <van-icon :name="item.is_like?'like':'like-o'" color="red"
                            @click.stop="like(item)" size="30px"/>
                </div>

              </div>
              <div class="img-box">
                        <span class="list-img" v-for="(user,index_1) in item.user_list.slice(0,3)" :key="index_1">
                        <van-image round width="50" height="50" :src="user.avatar"/>
                        </span>
                <span class="list-img" v-if="item.user_list.length>3">
                            <div class="list-end">+{{ item.user_list.length - 3 }}</div>
                        </span>
              </div>
            </div>
          </div>

        </div>
        <div>
          <van-button @click="sendWebSocket">发送socket</van-button>
          <van-button @click="getSocketState">获取状态</van-button>
        </div>
        <div class="no-user" v-show="raw_list.length===0">
          <div>暂时没有用户在听歌，请下拉刷新，或者搜索歌曲播放</div>
        </div>
      </div>

    </van-pull-refresh>
    <van-loading class="loading" type="spinner" v-show="!isInit"/>


  </div>
</template>

<script>
import api from "@/api/api";
import {convertImgUrl} from "@/utils/const";
import music from "@/api/music";
import Vue from 'vue'
import {Toast} from 'vant'

Vue.use(Toast)

export default {
  name: 'Home',
  data() {
    return {
      active: 'home',
      search_value: '',
      raw_list: [],
      is_play: "",
      timer: "",
      isLoading: false,
      isInit: false,
      socket: ''
    }
  },
  methods: {
    getSocketState() {
    },
    sendWebSocket() {
      let that = this
      try {
        this.socket = new WebSocket("ws://hbt123.xyz:8082/match/111")

        this.socket.onopen = function (a) {
          console.log("open.", a)
        }
        this.socket.onmessage = function (a) {
          console.log("message.", a)

        }
        this.socket.onerror = function (err) {
          console.log("Some errors occurred while connecting.", err)
        }
        this.socket.onclose = function (err) {
          console.log("Socket connection closed.", err.code)
          console.log("url is ", that.socket.url)
        }
      } catch (a) {
        console.log(a)
      }
    },
    onRefresh() {
      this.fresh()
    },
    fresh() {
      console.log("this")
      let that = this
      let t = setTimeout(() => {
        that.raw_list = []
        that.isLoading = false
        that.isInit = true
      }, 5000)
      api.getCurListen(1).then(res1 => {
        clearTimeout(t)
        that.raw_list = res1
        MiniApp.getSongs({
          album_audio_ids: res1.map(item1 => item1.music_id),
          success(res2) {
            res2.song_data_list.map((item2, index) => {
              that.raw_list[index].music_img = convertImgUrl(item2.album_sizable_cover || item2.authors[0].sizable_avatar)
              return item2
            })
            that.isLoading = false
            that.isInit = true
            console.log(that.isInit)
          }
        })
      });
    },
    playMusic(isPlay, music_id, music_name) {
      let that = this
      if (!isPlay) {
        music.playMusic(music_id, music_name).then(() => {
          that.timer = setInterval(() => {
            let info = music.getPlayerInfo()
            if (info.playStatus === 'play' | 'loading') {
              this.is_play = info.currentMixId
            } else this.is_play = ""
          }, 500)
        })
      } else {
        music.stopMusic().then(() => {
          clearInterval(that.timer)
        })
      }
    },
    like(music) {
      if (music.is_like) {
        music.is_like = false
        MiniApp.showToast({
          title: "取消收藏"
        })
        //TODO
      } else {
        music.is_like = true
        MiniApp.showToast({
          title: "收藏成功"
        })
        api.addToLike(music.music_id, music.music_name)
      }
    },
    toSongInfo(item) {
      MiniApp && MiniApp.setStorage({
        key: "songInfo",
        data: item,
        success: () => {
          MiniApp.navigateTo({
            url: "/songpage.html"
          })
        }
      })
    },
    onSearch() {
      let that = this
      let value = this.search_value
      if (this.search_value === '') {
        MiniApp.showToast({
          title: "请输入搜索的关键词",
          icon: "none",
          duration: 1000
        })
      } else {
        MiniApp && MiniApp.setStorage({
          key: "rawList",
          data: that.raw_list,
          success: () => {
            MiniApp && MiniApp.navigateTo({
              url: `/search.html?search=${value}`
            })
          }
        })
      }
      this.search_value = ''
    }
  },
  beforeMount() {
    let info = music.getPlayerInfo()
    this.is_play = info.currentMixId
    this.fresh()
  }
}
</script>

<style lang="scss" scoped>

.list-title {
  font-size: 36px;
}

.list-end {
  height: 3rem;
  width: 3rem;
  display: table-cell;
  background-color: pink;
  border-radius: 1.5rem;
  text-align: center;
  vertical-align: middle;
  font-size: 1.5rem;
}


.img-box {
  display: flex;
  margin-top: 1rem;
}

.list-item {
  background-color: #0190FD;
  border-radius: 0.5rem;
  padding: 0.5rem 0.8rem;
  margin-bottom: 30px;
}

.list-item:active {
  transform: translate(3px, 3px);
}

.list-item > .img-box > .list-img {
  margin-right: 0.4rem;
}

.tips {
  margin-top: 20px;
}

.songs {
  margin-top: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
}

.icon_group {
  display: flex;
}

.no-user {
  text-align: center;
  margin-top: 5rem;
}

.song-info {
  display: flex;
  align-items: center;
}
</style>